package com.dhcc.Interceptor;
import com.dhcc.api.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * 自定义拦截器，用于获取请求头信息
 * @ProjectName Dhcc-Cloud
 * @PackageName com.dhcc.Interceptor
 * @Title HeaderLoggingInterceptor
 * @Date 2024/10/31 上午3:36
 * @Author LiuGuoting
 */
@Component
public class HeaderLoggingInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(HeaderLoggingInterceptor.class);

    @Resource
    private final ObjectMapper objectMapper;

    public HeaderLoggingInterceptor(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String customHeaderValue = request.getHeader("X-Gateway-Header");
        if (customHeaderValue == null) {
            logger.error("非法请求，X-Gateway-Header 头信息不存在");
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            response.setContentType("application/json; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            R errorResponse = R.fail("非法请求，只允许通过网关访问");
            String jsonResponse = objectMapper.writeValueAsString(errorResponse);
            response.getWriter().write(jsonResponse);
            response.getWriter().flush();
            return false;
        }
        logger.info("Received X-Gateway-Header: {}", customHeaderValue);
        logger.info("合法请求，已校验请求为Gateway请求！");
        return true;
    }
}